﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using coffeeshop.coffeeDataSetTableAdapters;

namespace coffeeshop.Models
{
    public class Unit
    {
        private static UnitTableAdapter unitAdapter = new UnitTableAdapter();

        public string Name { get; set; }
        public int UnitId { get; private set; }
        public bool IsActive { get; set; }

        public Unit(){}
        public Unit(int _id) { UnitId = _id; }

        public static coffeeDataSet.UnitDataTable LoadUnits(bool toHideInactive)
        {
            return unitAdapter.GetUnitList(toHideInactive);
        }

        public bool UpdateActiveness()
        {
            try
            {
                int result = unitAdapter.UpdateActiveness(IsActive, UnitId);

                return result == 1;
            }
            catch
            {
                return false;
            }
        }

        public bool Save()
        {
            try
            {
                int result;
                if (UnitId == 0)
                {
                    coffeeDataSet.UnitDataTable existingUnit = unitAdapter.GetByName(Name);
                    if (existingUnit.Rows.Count > 0)
                    {
                        result = unitAdapter.UpdateUnit(Name, (int)existingUnit.Rows[0]["UnitId"]);
                    }
                    else
                        result = unitAdapter.AddUnit(Name);
                }
                else
                    result = unitAdapter.UpdateUnit(Name, UnitId);

                return result == 1;
            }
            catch
            {
                return false;
            }
        }
    }
}
